06. Exercise: Add Notifications to your App

L1 A06 Add Notification To Your App

Android Developer Documentation

Exercise

  1. Open AlarmReceiver.ktand get an instance of NotificationManager and call the sendNotification()function with message text and context parameters.
// AlarmReceiver.kt
        // TODO: Step 1.9 add call to sendNotification
        val notificationManager = ContextCompat.getSystemService(
            context, 
            NotificationManager::class.java
        ) as NotificationManager

        notificationManager.sendNotification(
            context.getText(R.string.eggs_ready).toString(), 
            context
        )
  1. Remove the Toast message since your app will be sending a notification when the timer is up.
// AlarmReceiver.kt
        // TODO: Step 1.10 [Optional] remove toast
//      Toast.makeText(
//          context, 
//          context.getText(R.string.eggs_ready),
//          Toast.LENGTH_SHORT
//      ).show()
  1. If you run the app now, you should see a notification every time you start the timer and every time the timer is up. This still doesn’t look right, you don’t want to send too many notifications to your users. You can remove the first notification which is sent when the user starts the timer.



  2. Open EggTimerViewModel and remove the notification code for Step 1.5.
// EggTimeViewModel.kt

// TODO: Step 1.5 get an instance of NotificationManager 
// and call sendNotification
// val notificationManager = ContextCompat.getSystemService(
//      app,
//      NotificationManager::class.java
// ) as NotificationManager
// notificationManager.sendNotification(app.getString(R.string.eggs_ready), app)
  1. Now if you run your app again, set a timer, put it in the background and wait for the time to finish, you will see a notification. This is a much more useful notification.

  2. Set a timer, put it in the background, and wait for the time to finish. You will see a notification. This is a much more useful notification.